package com.zerui.manager.app.accessauthdevice.executer;

import com.alibaba.cola.catchlog.CatchAndLog;
import com.alibaba.cola.exception.BizException;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zerui.cola.dto.Response;
import com.zerui.manager.accessauthdevice.AccessAuthDevice;
import com.zerui.manager.accessauthdevice.domainservice.AccessAuthDeviceRepository;
import com.zerui.manager.web.cmd.AccessAuthDeviceBindCmd;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author wh
 * @create_time 2023-08-29 14:34
 */
@Component
@CatchAndLog
public class AccessAuthDeviceAddCmdExe {

    @Resource
    private AccessAuthDeviceRepository accessAuthDeviceRepository;

    public Response execute(AccessAuthDeviceBindCmd cmd) {
        List<AccessAuthDevice> accessAuthDevices = accessAuthDeviceRepository.getByDeviceIds(cmd.getDeviceIds());
		if(CollectionUtils.isNotEmpty(accessAuthDevices)){
            accessAuthDevices.forEach(accessAuthDevice->{
                if(ObjectUtils.isNotEmpty(accessAuthDevice.getAccessAuthId())){
                    throw new BizException("存在设备已经被绑定");
                }
                accessAuthDevice.setAccessAuthId(cmd.getAccessAuthId());
            });
            List<Long> deviceIds = accessAuthDevices.stream().map(AccessAuthDevice::getDeviceId).collect(Collectors.toList());
            //设备权限下发
            accessAuthDeviceRepository.devicesDistributePermissions(cmd.getAccessAuthId(),deviceIds);
            return accessAuthDeviceRepository.updateBatch(accessAuthDevices);
		}
		return Response.buildSuccess();

    }
}
